package mwa.cs.hh.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.AllowanceDAO;
import mwa.cs.dao.ArDAO;
import mwa.cs.dao.CustHHDAO;
import mwa.cs.dao.CustMonthlyDAO;
import mwa.cs.dao.CustomerDAO;
import mwa.cs.dao.RouteScheduleMasterDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.dao.VatRateDAO;
import mwa.cs.database.Database;
import mwa.cs.hh.biz.MeterFunction;
import mwa.cs.model.Ar;
import mwa.cs.model.CustHH;
import mwa.cs.model.CustMonthly;
import mwa.cs.model.RouteScheduleMaster;
import mwa.cs.util.JDate;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class CS0303000Srvl
 */
public class CS33000Srvl extends HttpServlet implements Servlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private String vnZoneId;
	private String vnRouteId;
	private String vaAccount;
	private String vaPeriodMonth;
	private String vaPeriodYear;
	private int vnUserId;
	private String vaUrlAddress = "";
	private String vaAgentBrowser = "";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CS33000Srvl() {
		super();
	}

	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		vaUrlAddress = request.getParameter("url_address");
		vaAgentBrowser = request.getParameter("agent_browser");
		if (request.getParameter("process_type").equals("getDate")) {
			getDate(request, response);
		} else if (request.getParameter("process_type").equals("getDataTable")) {
			getDataTable(request, response);
		} else if (request.getParameter("process_type").equals("calculate")) {
			calculateWaterCharge(request, response);
		} else if (request.getParameter("process_type").equals("convertDate")) {
			convertDate(request, response);
		} else if (request.getParameter("process_type").equals("saveData")) {
			saveData(request, response);
		}

	}

	@SuppressWarnings({ "unchecked" })
	public void saveData(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter voOut = response.getWriter();
		JSONObject voObject = new JSONObject();
		if (request.getParameter("pnCurrentReadNumber") != null
				&& !request.getParameter("pnCurrentReadNumber").equals("")) {

			Database db = new Database();
			db.beginTransaction();
			CustHHDAO voCustHHDAO = new CustHHDAO(db);
			CustomerDAO voCustomerDAO = new CustomerDAO(db);
			ArDAO voArDAO = new ArDAO(db);
			CustMonthlyDAO voCustMonthlyDAO = new CustMonthlyDAO(db);
			RouteScheduleMasterDAO voRouteScheduleMasterDAO = new RouteScheduleMasterDAO(
					db);
			Map<String, Object> voMap = new HashMap<String, Object>();

			vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
			vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());

			int vnCurrentReadNumber = Integer.parseInt(request
					.getParameter("pnCurrentReadNumber"));
			int vnNewConsumption = Integer.parseInt(request
					.getParameter("pnNewConsumtion"));
			double vnNewAverageConsumption = Double.parseDouble(request
					.getParameter("pnNewAverageConsumtion").replace(",", ""));
			double vnVatAmount = Double.parseDouble(request.getParameter(
					"pnVatAmount").replace(",", ""));
			double vnWaterCharge = Double.parseDouble(request.getParameter(
					"pnWaterCharge").replace(",", ""));
			double vnWaterFee = Double.parseDouble(request.getParameter(
					"pnWaterFee").replace(",", ""));
			double vnBillAmount = Double.parseDouble(request.getParameter(
					"pnBillAmount").replace(",", ""));
			int vnNumberOfDay = Integer.parseInt(request.getParameter(
					"pnNumberOfDay").replace(",", ""));
			double vnTotalAmount = Double.parseDouble(request.getParameter(
					"pnTotalAmount").replace(",", ""));
			int vnZoneId = Integer.parseInt(request.getParameter("pnZoneId"));
			int vnRouteId = Integer.parseInt(request.getParameter("pnRouteId"));
			String vaAccount = request.getParameter("paAccount");
			String vaCurrentReadDate = JDate.saveDate(request
					.getParameter("paCurrentReadDate"));

			String periodMonth = voCustHHDAO.findMaxMonth(vnSiteId);
			String periodYear = voCustHHDAO.findMaxYear(vnSiteId);
			voMap = voCustHHDAO.findCustHHByAccount(vnSiteId, vaAccount, periodMonth, periodYear);

			String vaPeriodMonth = voCustHHDAO.findMaxMonth(vnSiteId);
			String vaPeriodYear = voCustHHDAO.findMaxYear(vnSiteId);
			int vnSeq = Integer.parseInt(voMap.get("SEQ").toString());
			String vaCustomerClas = voMap.get("CUSTOMER_CLASS").toString();
			String vaPName = null;
			if(voMap.get("PNAME") != null){
				vaPName = voMap.get("PNAME").toString();	
			}
			String vaFName = null;
			if(voMap.get("FNAME") != null){
				vaFName = voMap.get("FNAME").toString();
			}
			
			String vaLName = null;
			if(voMap.get("LNAME") != null){
				vaLName = voMap.get("LNAME").toString();	
			}
			String vaAddress = null ;
			if(voMap.get("ADDRESS") != null){
				vaAddress = voMap.get("ADDRESS").toString().replace("|", "");	
			}
			int vnSerialNumber = 0;
			String vaBillNumber = null ;
			if(voMap.get("BILL_NUMBER") != null){
				vaBillNumber = voMap.get("BILL_NUMBER").toString();
			}
			String vnBillType = "M";
			int vnConsumption = vnNewConsumption;
			String vaAllowance = null;
			if(voMap.get("ALLOWANCE") != null){
				vaAllowance = voMap.get("ALLOWANCE").toString();
			}
			int vnPreviousReadNumber;
			if (voMap.get("PREVIOUS_READ_NUMBER") == null) {
				vnPreviousReadNumber = 0;
			} else {
				vnPreviousReadNumber = Integer.parseInt(voMap.get(
						"PREVIOUS_READ_NUMBER").toString());
			}
			String vaPreviousReadDate;
			if (voMap.get("PREVIOUS_READ_DATE") == null) {
				vaPreviousReadDate = "00000000";
			} else {
				vaPreviousReadDate = voMap.get("PREVIOUS_READ_DATE").toString();
			}
			String vaAccountReceivableDate = JDate.getDate();
			String vaAccountReceivableTime = JDate.getTime();
			String vaStatus = null;
			String vaViodDate = null;
			String vaVoidTime = null;
			int vnViodEmployee = 0;
			String vaReceiveDate = null;
			String vaReceiveTime = null;
			int vnReceiveEmployee = 0;
			String vaPayBy = null;
			int vnPrintBillNumber = 0;
			String vaReason = null;
			double vnGarbageCharge = Double.parseDouble(voMap.get(
					"GARBAGE_CHARGE").toString());
			double vnWasteWaterCharge = Double.parseDouble(voMap.get(
					"WASTEWATER_CHARGE").toString());
			double vnOtherCharge = Double.parseDouble(voMap.get("OTHER_CHARGE")
					.toString());
			int vnPrintSerialNumber = 0;
			int vnInsertUserId = vnUserId;
			String vaInsertDate = JDate.getDate();
			String vaInsertTime = JDate.getTime();
			int vnUpdateUserId = 0;
			String vaUpdateDate = null;
			String vaUpdateTime = null;
			String vaCustomerClass = null;
			if(voMap.get("CUSTOMER_CLASS") != null){
				vaCustomerClass = voMap.get("CUSTOMER_CLASS").toString();	
			}
			String vaMeterNumber = null;
			if(voMap.get("METER_NUMBER") != null){
				vaMeterNumber = voMap.get("METER_NUMBER").toString();
			}
			String vaMeterReadNumber = "" + vnCurrentReadNumber;
			String vaReadDate = vaCurrentReadDate;
			double vnAverageConsumption = vnNewAverageConsumption;
			String vaCommentCode = null;

			Ar poAr = new Ar(vnSiteId, vnZoneId, vnRouteId, vaAccount,
					vaPeriodMonth, vaPeriodYear, vnSeq, vaCustomerClas,
					vaPName, vaFName, vaLName, vaAddress, vnSerialNumber,
					vaBillNumber, vnBillType, vnConsumption, vaAllowance,
					vnWaterFee, vnWaterCharge, vnVatAmount, vnBillAmount,
					vnPreviousReadNumber, vaPreviousReadDate,
					vaCurrentReadDate, vnCurrentReadNumber,
					vaAccountReceivableDate, vaAccountReceivableTime, vaStatus,
					vaViodDate, vaVoidTime, vnViodEmployee, vaReceiveDate,
					vaReceiveTime, vnReceiveEmployee, vaPayBy,
					vnPrintBillNumber, vnTotalAmount, vaReason,
					vnGarbageCharge, vnWasteWaterCharge, vnOtherCharge,
					vnPrintSerialNumber, vnInsertUserId, vaInsertDate,
					vaInsertTime, vnUpdateUserId, vaUpdateDate, vaUpdateTime);

			voMap = voCustomerDAO.getCustomer(vnSiteId, vaAccount);
			if(voMap.get("STATUS") != null){
				vaStatus = voMap.get("STATUS").toString();	
			}

			CustMonthly poCustMonthly = new CustMonthly(vnSiteId, vnZoneId,
					vnRouteId, vaAccount, vaPeriodMonth, vaPeriodYear, vnSeq,
					vaCustomerClass, vaBillNumber, vaMeterNumber,
					vaMeterReadNumber, vaReadDate, vnConsumption,
					vnAverageConsumption, vaAllowance, vnWaterFee,
					vnWaterCharge, vnVatAmount, vnBillAmount, vaCommentCode,
					vaStatus, vnInsertUserId, vaInsertDate, vaInsertTime,
					vnUpdateUserId, vaUpdateDate, vaUpdateTime);

			CustHH poCustHH = new CustHH();
			poCustHH.setVnAveragevnConsumptionNew(vnNewAverageConsumption);
			poCustHH.setVnNewConsumption(vnNewConsumption);
			poCustHH.setVaCurrentReadDate(vaCurrentReadDate);
			poCustHH.setVnCurrentReadNumber(vnCurrentReadNumber);
			poCustHH.setVaStatus("2");
			poCustHH.setVnWaterCharge(vnWaterCharge);
			poCustHH.setVnWaterFee(vnWaterFee);
			poCustHH.setVnVatAmount(vnVatAmount);
			poCustHH.setVnBillAmount(vnBillAmount);
			poCustHH.setVaUploadDate(JDate.getDate());
			poCustHH.setVaUploadTime(JDate.getTime());
			poCustHH.setVaAccountReceivableDate(JDate.getDate());
			poCustHH.setVaAccountReceivableTime(JDate.getTime());
			poCustHH.setVnNumberfDay(vnNumberOfDay);
			poCustHH.setVnUpdateUserId(vnUserId);
			poCustHH.setVaUpdateDate(JDate.getDate());
			poCustHH.setVaUpdateTime(JDate.getTime());
			poCustHH.setVnSiteId(vnSiteId);
			poCustHH.setVnZoneId(vnZoneId);
			poCustHH.setVnRouteId(vnRouteId);
			poCustHH.setVaAccount(vaAccount);
			poCustHH.setVaPeriodMonth(vaPeriodMonth);
			poCustHH.setVaPeriodYear(vaPeriodYear);

			RouteScheduleMaster poRouteScheduleMaster = new RouteScheduleMaster();
			poRouteScheduleMaster.setVnSiteId(vnSiteId);
			poRouteScheduleMaster.setVnZoneId(vnZoneId);
			poRouteScheduleMaster.setVnRouteId(vnRouteId);
			poRouteScheduleMaster.setVaPeriodMonth(vaPeriodMonth);
			poRouteScheduleMaster.setVaPeriodYear(vaPeriodYear);
			poRouteScheduleMaster.setVaUploadDate(JDate.getDate());
			poRouteScheduleMaster.setVaUploadTime(JDate.getTime());
			int vnTotalUpload = voRouteScheduleMasterDAO
					.getTotalUpload(poRouteScheduleMaster) + 1;
			poRouteScheduleMaster.setVnTotalUpload(vnTotalUpload);

			try {

				voArDAO.insertAr(poAr);
				voCustMonthlyDAO.insertCustMonthly(poCustMonthly);
				voCustHHDAO.updateCustHHByRoute(poCustHH);
				voRouteScheduleMasterDAO
						.updateRouteScheduleMaster(poRouteScheduleMaster);
				db.commit();
				voObject.put("success", "true");
				voOut.print(voObject.toJSONString());
				
			} catch (Exception e) {
				db.rollback();
				SMErrorLogDAO.getInstance().addLog(0, "CS33000", JDate.getDate(), JDate.getTime(),vnUserId, "CS33000Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);	
			}

		}else{
			voObject.put("success", "false");	
		}
		voOut.print(voObject.toJSONString());
	}

	@SuppressWarnings({ "unchecked", "static-access" })
	public void convertDate(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String paDate = request.getParameter("paDate");
		PrintWriter out = response.getWriter();
		JSONObject voObject = new JSONObject();
		JDate voJDate = new JDate();

		voObject.put("paDate", voJDate.saveDate(paDate));
		out.print(voObject.toJSONString());
	}

	@SuppressWarnings("unchecked")
	public void getDate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		Database db = new Database();
		PrintWriter out = response.getWriter();
		JSONObject voObject = new JSONObject();
		CustHHDAO voCustHHDAO = new CustHHDAO(db);

		String maxMonth = voCustHHDAO.findMaxMonth(vnSiteId);
		String maxYear = voCustHHDAO.findMaxYear(vnSiteId);
		voObject.put("maxMonth", maxMonth);
		voObject.put("maxYear", maxYear);
		out.print(voObject.toJSONString());
	}

	@SuppressWarnings("unchecked")
	public void getDataTable(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Database db = new Database();
		CustHHDAO voCustHHDAO = new CustHHDAO(db);
		RouteScheduleMasterDAO voRSMManagement = new RouteScheduleMasterDAO(db);
		PrintWriter out = response.getWriter();
		List<Map<String, Object>> voList = new ArrayList<Map<String, Object>>();
		Map<String, Object> voMap = new HashMap<String, Object>();

		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());

		vnZoneId = request.getParameter("sSearch_0").trim();
		vnRouteId = request.getParameter("sSearch_1").trim();
		vaAccount = request.getParameter("sSearch_2").trim();
		boolean vbSearch = false;
		if (!vnZoneId.equals("") || !vnRouteId.equals("")
				|| !vaAccount.equals("")) {
			vbSearch = true;
		}
		if (vbSearch == false && vaAccount.equals("")) {
			vaAccount = "-1";
		}
		vaPeriodMonth = voCustHHDAO.findMaxMonth(vnSiteId);
		vaPeriodYear = voCustHHDAO.findMaxYear(vnSiteId);

		int vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); // 0
		int vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
		int vnEnd = vnStart + vnAmount;
		int vnTotalDisplayRecords = 0;
		int vnTotalRecords = voCustHHDAO.getCountAllCustHHByRoute(vnSiteId, vnZoneId, vnRouteId, vaAccount, vaPeriodMonth, vaPeriodYear);

		if (vnAmount == -1 && vbSearch == true) {
			String vaDownloadDate = voRSMManagement.findDownloadDate(vnSiteId, Integer.parseInt(vnZoneId), Integer.parseInt(vnRouteId), vaPeriodMonth, vaPeriodYear);
			if (vaDownloadDate != null){
				voList = voCustHHDAO.findAllCustHHByRoute(vnSiteId, vnZoneId, vnRouteId, vaAccount, vaPeriodMonth, vaPeriodYear);
				}	
			vnTotalDisplayRecords = vnTotalRecords;

		} else if (vbSearch == true) {
			String vaDownloadDate = voRSMManagement.findDownloadDate(vnSiteId, Integer.parseInt(vnZoneId), Integer.parseInt(vnRouteId), vaPeriodMonth, vaPeriodYear);
				if (vaDownloadDate != null){
					voList = voCustHHDAO.findCustHHByRoute(vnSiteId, vnZoneId, vnRouteId, vaAccount, vaPeriodMonth, vaPeriodYear, vnStart,vnEnd);
					}
			vnTotalDisplayRecords = vnTotalRecords;
		}

		JSONObject voObject = new JSONObject();
		JSONArray voListData = new JSONArray();
		JSONArray voArray = new JSONArray();
		JSONArray voAccount = new JSONArray();
		for (int i = 0; i < voList.size(); i++) {
			voArray = new JSONArray();
			voMap = voList.get(i);
			voArray.add((String) "" + voMap.get("SEQ"));
			voArray.add((String) "" + voMap.get("ZONE_NAME"));
			voArray.add((String) "" + voMap.get("ROUTE_DESCRIPTION"));
			voAccount = new JSONArray();
			voAccount.add(i);
			voAccount.add(voMap.get("ACCOUNT"));
			if (voMap.get("PREVIOUS_READ_DATE") == null) {
				voAccount.add((String) voMap.get("PERIOD_YEAR")
						+ voMap.get("PERIOD_MONTH") + "01");
			} else {
				voAccount.add((String) "" + voMap.get("PREVIOUS_READ_DATE"));
			}
			voArray.add(voAccount);
			if (voMap.get("PREVIOUS_READ_DATE") == null) {
				voArray.add((String) "00/00/0000");
			} else {
				voArray.add((String) ""
						+ JDate.showDate(voMap.get("PREVIOUS_READ_DATE")
								.toString()));
			}
			if (voMap.get("PREVIOUS_READ_NUMBER") == null) {
				voArray.add((String) "0");
			} else {
				voArray.add((String) "" + voMap.get("PREVIOUS_READ_NUMBER"));
			}
			voArray.add((String) "" + voMap.get("ACCOUNT"));
			voArray.add((String) "" + voMap.get("ACCOUNT"));
			voArray.add((String) "" + voMap.get("ACCOUNT"));
			voArray.add((String) "" + voMap.get("ACCOUNT"));
			voArray.add((String) "" + voMap.get("ACCOUNT"));

			voListData.add(voArray);
		}

		voObject.put("iTotalRecords", vnTotalRecords);
		voObject.put("iTotalDisplayRecords", vnTotalDisplayRecords);
		voObject.put("aaData", voListData);
		out.print(voObject.toJSONString());

	}

	@SuppressWarnings({ "static-access", "unchecked" })
	public void calculateWaterCharge(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());

		Database db = new Database();
		CustHHDAO voCustHHDAO = new CustHHDAO(db);
		VatRateDAO voVatRateDAO = new VatRateDAO(db);
		Map<String, Object> voMap = new HashMap<String, Object>();
		MeterFunction voMeterFunction = new MeterFunction();
		JDate voJDate = new JDate();
		PrintWriter out = response.getWriter();
		JSONObject voObject = new JSONObject();
		DecimalFormat formatter = new DecimalFormat("#,###,###.00");
		if (request.getSession().getAttribute("site_id") != null) {
			vnSiteId= Integer.parseInt(""
					+ request.getSession().getAttribute("site_id"));
		} else {
			vnSiteId = 1;
		}
		vaAccount = request.getParameter("paAccount");
		String vaCalculation = request.getParameter("paCalculation");
		String paPreviousReadDate = request.getParameter("paPreviousReadDate");
		String paCurrentReadDate = request.getParameter("paCurrentReadDate");

		double pnUsedUnit = Double.parseDouble(request
				.getParameter("pnConsumtion"));
		String paCustomerClass = null;

		int vnAllowance = 0;
		int vnNewConsumtion = 0;
		int vnNumberOfDay = 1;
		String vaAllowanceType = null;
		double vnAllowanceDiscount = 0;
		double vnWaterCharge = 0;
		double vnTotalAmount = 0;
		double vnVatRate = 0;
		double vnNewAverageConsumtion = 0;
		double vnWaterFee = 0;
		double vnVatAmount = 0;
		double vnBillAmount = 0;
		double vnGarbangCharge = 0;
		double vnWasteWaterCharge = 0;
		double vnOtherCharge = 0;

		voMap = new HashMap<String, Object>();
		voMap = voVatRateDAO.getVatRate(vnSiteId,
				voJDate.saveDate(paCurrentReadDate));
		if (voMap.get("RATE").toString() != null) {
			vnVatRate = Double.parseDouble(voMap.get("RATE").toString());
		}

		voMap = new HashMap<String, Object>();
		String periodMonth = voCustHHDAO.findMaxMonth(vnSiteId);
		String periodYear = voCustHHDAO.findMaxYear(vnSiteId);
		voMap = voCustHHDAO.findCustHHByAccount(vnSiteId, vaAccount, periodMonth, periodYear);
		paCustomerClass = voMap.get("CUSTOMER_CLASS").toString();
		if (voMap.get("FEE") != null) {
			vnWaterFee = Double.parseDouble(voMap.get("FEE").toString());
		}
		if (voMap.get("ALLOWANCE") != null) {
			vnAllowance = Integer.parseInt(voMap.get("ALLOWANCE").toString());
		}
		vnGarbangCharge = Double.parseDouble(voMap.get("GARBAGE_CHARGE")
				.toString());
		vnWasteWaterCharge = Double.parseDouble(voMap.get("WASTEWATER_CHARGE")
				.toString());
		vnOtherCharge = Double
				.parseDouble(voMap.get("OTHER_CHARGE").toString());

		if (vaCalculation.equals("average")) {
			try {

				if (!paPreviousReadDate.equals("00/00/0000")) {
					String vaAverageUnitPerDay = voMeterFunction
							.calculateAverageConsumption(vnSiteId, vaAccount);
					vnNumberOfDay = Integer.parseInt(voMeterFunction
							.CalDurationBetweenTwoDates(paPreviousReadDate,
									paCurrentReadDate));

					pnUsedUnit = Double.parseDouble(vaAverageUnitPerDay
							.replace(",", "")) * vnNumberOfDay;

					

				} else {

					pnUsedUnit = 0;
				}
				voObject.put("Calculation", "average");

			} catch (ParseException e) {
				SMErrorLogDAO.getInstance().addLog(0, "CS33000", JDate.getDate(), JDate.getTime(),vnUserId, "CS33000Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);	
				e.printStackTrace();
			}
		}
		if (paPreviousReadDate.equals("00/00/0000")) {
			vaPeriodMonth = voCustHHDAO.findMaxMonth(vnSiteId);
			vaPeriodYear = voCustHHDAO.findMaxYear(vnSiteId);
			paPreviousReadDate = "01/" + vaPeriodMonth + "/" + vaPeriodYear;
			try {
				vnNumberOfDay = Integer.parseInt(voMeterFunction
						.CalDurationBetweenTwoDates(paPreviousReadDate,
								paCurrentReadDate));
			} catch (NumberFormatException e) {
				SMErrorLogDAO.getInstance().addLog(0, "CS33000", JDate.getDate(), JDate.getTime(),vnUserId, "CS33000Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);	
				e.printStackTrace();
			} catch (ParseException e) {
				SMErrorLogDAO.getInstance().addLog(0, "CS33000", JDate.getDate(), JDate.getTime(),vnUserId, "CS33000Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);	
				e.printStackTrace();
			}
		}
		if (vnAllowance == 1) {
			AllowanceDAO voAllowanceDAO = new AllowanceDAO(db);
			voMap = new HashMap<String, Object>();
			voMap = voAllowanceDAO.getAllowance(vnSiteId);
			vaAllowanceType = voMap.get("TYPE").toString();
			vnAllowanceDiscount = Double.parseDouble(voMap.get("DISCOUNT")
					.toString());
			if (vaAllowanceType.equals("W") || vaAllowanceType.equals("w")) {
				String vnWaterChargeTemp = voMeterFunction
						.calNormalUsedUnitWater(vnSiteId, paCustomerClass,
								pnUsedUnit);
				vnWaterCharge = Double.parseDouble(vnWaterChargeTemp.replace(
						",", ""));

				vnWaterCharge = vnWaterCharge - vnAllowanceDiscount;
				
			} else {

				pnUsedUnit = pnUsedUnit - (pnUsedUnit * vnAllowanceDiscount);
				String vnWaterChargeTemp = voMeterFunction
						.calNormalUsedUnitWater(vnSiteId, paCustomerClass,
								pnUsedUnit);
				vnWaterCharge = Double.parseDouble(vnWaterChargeTemp.replace(
						",", ""));
			}
		} else {

			String vnWaterChargeTemp = voMeterFunction.calNormalUsedUnitWater(
					vnSiteId, paCustomerClass, pnUsedUnit);
			vnWaterCharge = Double.parseDouble(vnWaterChargeTemp.replace(",",
					""));
		}
		vnNewConsumtion = (int) Math.round(pnUsedUnit);
		//vnNewAverageConsumtion = vnNewConsumtion / vnNumberOfDay;
		vnNewAverageConsumtion = Double.parseDouble(MeterFunction.calculateAverageConsumption(vnSiteId, vaAccount));
		vnVatAmount = vnVatRate * (vnWaterCharge + vnWaterFee);
		vnBillAmount = vnWaterCharge + vnWaterFee + vnVatAmount;
		vnTotalAmount = vnWaterCharge + vnWaterFee + vnVatAmount
				+ vnGarbangCharge + vnWasteWaterCharge + vnOtherCharge;

		voObject.put("NewConsumtion", vnNewConsumtion);
		voObject.put("NewAverageConsumtion", vnNewAverageConsumtion);
		voObject.put("VatAmount", formatter.format(vnVatAmount));
		voObject.put("WaterCharge", formatter.format(vnWaterCharge));
		voObject.put("WaterFee", formatter.format(vnWaterFee));
		voObject.put("BillAmount", formatter.format(vnBillAmount));
		voObject.put("NumberOfDay", vnNumberOfDay);
		voObject.put("TotalAmount", formatter.format(vnTotalAmount));

		out.print(voObject.toJSONString());

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
